package com.example.voiceassistant.monitoring;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 监控服务的简化实现，仅提供计数器能力。
 */
public class MonitoringService {

    private static final Logger LOGGER = LoggerFactory.getLogger(MonitoringService.class);

    private final Map<String, Counter> counters = new ConcurrentHashMap<>();

    public Counter counter(String name) {
        Counter counter = counters.computeIfAbsent(name, AtomicLongCounter::new);
        return counter;
    }

    public void gauge(String name, long value) {
        LOGGER.debug("Gauge [{}] = {}", name, value);
    }

    public void event(String name, String message) {
        LOGGER.info("Event [{}] {}", name, message);
    }

    public interface Counter {
        void increment();

        void increment(long delta);

        long value();
    }

    private static class AtomicLongCounter implements Counter {
        private final String name;
        private final AtomicLong value = new AtomicLong();

        private AtomicLongCounter(String name) {
            this.name = name;
        }

        @Override
        public void increment() {
            increment(1);
        }

        @Override
        public void increment(long delta) {
            long current = value.addAndGet(delta);
            LOGGER.debug("Counter [{}] -> {}", name, current);
        }

        @Override
        public long value() {
            return value.get();
        }
    }
}

